package com.handa.common.utils;

import lombok.Data;

import java.lang.reflect.Field;
import java.util.*;

public class ObjectPropertyUtils {

    /**
     * 获取对象所有属性及值
     *
     * @param obj 目标对象
     * @return 属性Map
     */
    public static Map<String, Object> getPropertyMap(Object obj) throws IllegalAccessException {
        Map<String, Object> propertyMap = new HashMap<>();
        Class<?> clazz = obj.getClass();

        // 获取所有字段(包括父类)
        for (Field field : getAllFields(clazz)) {
            field.setAccessible(true); // 设置可访问私有字段
            Object value = field.get(obj);
            propertyMap.put(field.getName(), value);
        }

        return propertyMap;
    }

    /**
     * 获取类及其父类的所有字段
     */
    private static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        while (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

    /**
     * 将对象属性转为可存储的Property列表
     */
    public static List<PropertyItem> convertToPropertyItems(Object obj, String objectId) throws IllegalAccessException {
        Map<String, Object> propertyMap = getPropertyMap(obj);
        List<PropertyItem> items = new ArrayList<>();

        for (Map.Entry<String, Object> entry : propertyMap.entrySet()) {
            PropertyItem item = new PropertyItem();
            item.setObjectId(objectId);
            item.setPropertyKey(entry.getKey());
            item.setPropertyValue(entry.getValue() != null ? entry.getValue().toString() : null);
            item.setPropertyType(entry.getValue() != null ? entry.getValue().getClass().getSimpleName() : "null");
            items.add(item);
        }

        return items;
    }

    // PropertyItem实体类
    @Data
    public static class PropertyItem {
        private String objectId;
        private String propertyKey;
        private String propertyValue;
        private String propertyType;

    }
}